package com.zhengf.rdf.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zhengf.rdf.annotation.UserLoginToken;
import com.zhengf.rdf.entity.User;
import com.zhengf.rdf.service.TokenService;
import com.zhengf.rdf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhengf
 * @since 2019-01-23
 */
@CrossOrigin
@RestController
@RequestMapping("/login")
public class LoginController {

   // @Autowired
   // private ILoginService loginSer;
    @Autowired
    private UserService userSer;
    @Autowired
    private TokenService tokenService;


    @PostMapping(value = "/in")
    public JSONObject saveUser(@RequestParam("username") String username, @RequestParam("password") String password) {
        JSONObject jsonObject=new JSONObject();
        User user = new User();
        user.setUserName(username);
        user.setPassword(password);
        EntityWrapper ew = new EntityWrapper();
        ew.setEntity(user);
        int i = userSer.selectCount(ew);

        if(i == 0){
            jsonObject.put("status", "false");
            jsonObject.put("message","登录失败,用户名或密码错误");
            return jsonObject;
        }else {
            String token = tokenService.getToken(user);
            User user1 = new User();
            user1.setLastLoginTime(new Date());
            user1.setUserName(username);
            user1.setPassword(password);

            User user2 = new User();
            user2.setUserName(username);
            user2.setPassword(password);
            userSer.update(user1,new EntityWrapper<>(user2));

            jsonObject.put("token", token);
            jsonObject.put("user", user);
            jsonObject.put("message", "true");
            jsonObject.put("status", "true");

            return jsonObject;
        }

    }

    @UserLoginToken
    @PostMapping("/getMessage")
    public JSONObject getMessage(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("message", "true");
        return jsonObject;
    }
}
